import { Type } from "protobufjs";

export default class Utility {
    /**
     * 连接字符串
     * @param content 文本
     * @param args    参数
     * @returns 
     */
    public static Concat(content: string, ...args: any[]): string {
        try {
            return content.concat(...args);
        }
        catch {
            cc.log("错误的字符串:", content);
        }
    }

    /**
     * 填充字符串
     * @param content 文本
     * @param args    参数
     * @returns 
     */
    public static Format(content: string, ...args: any[]): string {
        try {
            for (var i = 0; i < args.length; i++) {
                content = content.replace("{" + i + "}", args[i]);
            }
            return content;
        }
        catch {
            cc.log("错误的字符串:", content);
        }
    }

    /**
     * 单个节点正常/置灰材质
     * @param tempNode 节点
     * @param isGray   true置灰 false正常
     */
    public static setMaterial(tempNode: cc.Node, isGray: boolean) {
        let material = isGray ? cc.Material.getBuiltinMaterial("2d-gray-sprite") : cc.Material.getBuiltinMaterial("2d-sprite");
        let renderComponent = tempNode.getComponent(cc.RenderComponent);
        if (renderComponent) {
            renderComponent.setMaterial(0, material);
        }
    }

    /**
     * 根及孩子节点正常/置灰材质
     * @param tempNode 节点
     * @param isGray   true置灰 false正常
     */
    public static setAllMaterial(tempNode: cc.Node, isGray: boolean) {
        let material = isGray ? cc.Material.getBuiltinMaterial("2d-gray-sprite") : cc.Material.getBuiltinMaterial("2d-sprite");
        let renderComponents = tempNode.getComponentsInChildren(cc.RenderComponent);
        renderComponents.forEach((value, index) => {
            value.setMaterial(0, material);
        })
    }

    /**
     * 获取对象的属性个数或长度
     * @param obj 
     * @returns 
     */
    public static getPropertyCount(obj: Object) {
        let index: string;
        let count: number = 0;
        for (index in obj) {
            if (obj.hasOwnProperty(index)) {
                count++;
            }
        }
        return count;
    }
    
    /**
     * 对象的深度克隆
     * @param target 克隆对象
     * @returns 
     */
    public static clonUtil(target: any) {
        let result: any = null;
        if (Utility.getType(target) === "Object") {
            result = {};
        }
        else if (Utility.getType(target) === "Array") {
            result = [];
        }
        else {
            return target;
        }

        for (let i in target) {
            let item = target[i];
            if (Utility.getType(item) === "Object" || Utility.getType(item) === "ObjArrayect") {
                result[i] = Utility.clonUtil(item);
            }
            else { result[i] = item; }
        }
        return result;
    }
    private static getType(target: any) { return Object.prototype.toString.call(target).slice(8, -1) }
}
